package com.example.finalwork2.controller;



import com.example.finalwork2.entity.VehicleSignal;
import com.example.finalwork2.service.VehicleSignalService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;


//这个接口用来接收车辆信号数据，以及查询车辆的电池信号状态
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class VehicleSignalController {

   // private final JedisPool jedisPool;


    @Autowired
    private VehicleSignalService vehicleSignalService;
    //private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule());


    @PostMapping("/upload")
    public ResponseEntity<String> uploadVehicleSignals(@RequestBody List<VehicleSignal> signalList) {
        try {
            vehicleSignalService.saveVehicleSignals(signalList);
            return ResponseEntity.ok("信号已成功上传并存储到 Redis");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败：" + e.getMessage());
        }
//        try (Jedis jedis = jedisPool.getResource()) {
//            for (VehicleSignal signal : signalList) {
//
//                signal.setReportTime(LocalDateTime.now());
//
//                String key = "vehicle:signal:" + signal.getVehicleId();
//                long score = signal.getReportTime().toEpochSecond(ZoneOffset.UTC);
//
//                String value = objectMapper.writeValueAsString(signal);
//                jedis.zadd(key, score, value);
//
//            }
//            return ResponseEntity.ok("信号已成功上传并存储到 Redis");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败：" + e.getMessage());
//        }
    }

    @GetMapping("/signal/{vehicleId}")
    public ResponseEntity<List<VehicleSignal>> getLatestSignals(
            @PathVariable String vehicleId,
            @RequestParam(defaultValue = "10") int limit
    ) {
        List<VehicleSignal> result = vehicleSignalService.getLatestSignals(vehicleId, limit);
        return ResponseEntity.ok(result);

//        String redisKey = "vehicle:signal:" + vehicleId;
//        List<VehicleSignal> result = new ArrayList<>();
//
//        try (Jedis jedis = jedisPool.getResource()) {
//            // 1. 先从 Redis 中获取
//            List<String> jsonList = jedis.zrevrange(redisKey, 0, limit - 1);
//
//            for (String json : jsonList) {
//                try {
//                    VehicleSignal signal = objectMapper.readValue(json, VehicleSignal.class);
//                    result.add(signal);
//                } catch (Exception ex) {
//                    ex.printStackTrace();
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        int missingCount = limit - result.size();
//
//        // 2. Redis 不足，从数据库补齐
//        if (missingCount > 0) {
//
//
//            List<VehicleSignal> dbList = vehicleSignalService.getLatestByVehicleId(vehicleId, missingCount);
//
//
//            Set<Long> existingIds = result.stream()
//                    .map(VehicleSignal::getId)
//                    .filter(Objects::nonNull)
//                    .collect(Collectors.toSet());
//
//
//            for (VehicleSignal signal : dbList) {
//                if (!existingIds.contains(signal.getId())) {
//                    result.add(signal);
//                }
//            }
//        }
//
//        return ResponseEntity.ok(result);
    }




}
